#include <iostream>
#include <fstream>
#include <thread>
#include "mockmessagehandler.h"
#include "zmq_messenger.h"
#include "loghelper.h"
#include "serialize.hpp"
#include "video_bbox_drawer.h"

using namespace RockLog;


void MockMessageHandler::doWorkerUploadVideoAndTracks(BytesBuffer& buf)
{
    // deserialize string
    std::istringstream is(buf.retrieveAllAsString());
    VideoAndTracks_t t;
    deserialize(is, t.tracksStr);
    deserialize(is, t.videoName);
    deserialize(is, t.videoData);

    std::ofstream f(t.videoName, std::ofstream::binary);
    f << t.videoData;
    f.close();
    std::string outputVideo = "out_" + t.videoName + ".mp4";
    drawBBoxOnVideo(t.videoName.c_str(), t.tracksStr.c_str(), t.tracksStr.length(), outputVideo.c_str());
    LOG(kInfo) << "write outputVideo: " << outputVideo;
}

void MockMessageHandler::onRecvMsg(const char * workerId, const char *msg, uint32_t len)
{
    LOG(kInfo) << "[MockMessageHandler::onRecvMsg]";
    BytesBuffer buf;
    uint32_t type;  //
    char recvId[5] = {0};
    buf.append(msg, len);
    buf.retrieve(recvId, 4);

    if (workerId != std::string(recvId))
    {
        LOG(kErr) << "invalid workerId:" << recvId;
        return;
    }

    buf.retrieve((char *)&type, 4);
    LOG(kInfo) << "type: " << type;
    switch (type)
    {
    case kJsonMessage:
        LOG(kInfo) << "receive json message";
        break;
    case kStringMessage:
        LOG(kInfo) << "receive string message";
        break;
    case kWorkerUploadVideoAndTracks_t:
        LOG(kInfo) << "receive kWorkerUploadVideoAndTracks_t";
        doWorkerUploadVideoAndTracks(buf);
        break;
    default:
        LOG(kInfo) << "MockMessageHandler::onRecvMsg xxxx";
        break;
    }
}
